package com.bang.controller;

import com.bang.utils.ActiveUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

/**
 * 用户登陆控制器
 * @Author: bangbang
 * @Date: 2020/5/14 19:39
 */
@RequestMapping("login")
@Controller
public class loginController {

    /**
     * 跳转到登陆页面
     * @return
     */
    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }

    /**
     * 登陆
     * @param username
     * @param pwd
     * @param session
     * @return
     */
    @RequestMapping("login")
    public String login(String username, String pwd, HttpSession session){
        //得到主体
        Subject subject = SecurityUtils.getSubject();
        //System.out.println(username+"-----"+pwd);
        //System.out.println(subject);
        //111111111111
        AuthenticationToken token=new UsernamePasswordToken(username,pwd);
        try {
            subject.login(token);
            System.out.println("登陆成功");
            ActiveUser activeUser =(ActiveUser) subject.getPrincipal();
            session.setAttribute("user",activeUser.getUser());
            return "redirect:/book/allBook";
        } catch (AuthenticationException e) {
            session.setAttribute("error","验证失败，请重新输入！");
            return "redirect:/index.jsp";
        }
    }

}
